﻿namespace MDXStudio
{
    using MDXParser;
    using Microsoft.AnalysisServices.AdomdClient;
    using System;

    internal class QueryContext : MDXStudio.Context
    {
        public MDXSelectNode m_Select;

        public void SetSelect(MDXSelectNode select, AdomdConnection Connection, string cube)
        {
            this.m_Select = select;
            base.StartContext(Connection, cube);
            AdomdCommand command = Connection.CreateCommand();
            if (select.Params != null)
            {
                foreach (MDXParameter parameter in select.Params)
                {
                    command.Parameters.Add(parameter.Name, parameter.Value);
                }
            }
            foreach (MDXWithNode node in select.Withs)
            {
                command.CommandText = string.Format("CREATE {0}", node.GetMDXWithCube(cube));
                command.ExecuteNonQuery();
            }
            if (select.Where != null)
            {
                command.CommandText = string.Format("SELECT {{ {0} }} ON 0, {{}} ON 1 FROM [{1}]", select.Where.GetDebugMDX(), cube);
                CellSet set = command.ExecuteCellSet();
                if (set.Axes[0].Positions.Count > 0)
                {
                    base.UpdateCoordinates(set.Axes[0].Positions[0], set.OlapInfo.AxesInfo.Axes[0]);
                }
            }
        }
    }
}

